/** Access Cheval DB through thin driver, and introduce ResultSetMetaData class.
	1. Download thin JDBC driver from Oracle.
	2. ResultSetMetaData interface is implemented by driver provider. The meta data
	   provide methods for accessing properties of table columns such as
		-- nnumber of columns, column names and types,
		-- precision and scale
		-- is column readable, writable, searchable and etc.
    The example uses meta data to access number of column of result set and column
headings of a result set.
*/

import java.sql.*;
import java.io.*;

public class ShowPlanTable {

	Connection cnn;
	Statement  stmt;
	ResultSet  res;
	ResultSetMetaData meta;

	String url = "jdbc:oracle:thin:@prover.cs.csubak.edu:1521:PROVERDB",
		 user="gradebook", passwd="c3m4p2s";

	public ShowPlanTable() {
	   try {
               // Class.forName(driverName);
		DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		cnn = DriverManager.getConnection(url, user, passwd);
		stmt = cnn.createStatement();
	   } catch (SQLException e ) { e.printStackTrace(); System.exit(-1); }
	}

	public static void main(String argv[]) {
		ShowPlanTable ex5 = new ShowPlanTable(); // get connected, and create stmt.
		String	sql;
		sql = "SELECT * FROM plan_table";
		ex5.executeSQL(sql);
		ex5.displayResultSet();
	}

	void executeSQL(String sql) {
	   try {
		System.out.println("\n");
		res = stmt.executeQuery(sql);
		meta = res.getMetaData();
	   } catch (SQLException e) { e.printStackTrace(); }
	}

	void displayResultSet() {
	   try {
		int colCnt = meta.getColumnCount();
		String ans = null;		
		while ( res.next() ) {
			for ( int i = 1; i <= colCnt; i ++ ) {
			        System.out.print( ScreenIO.expandString(25, meta.getColumnName(i)));
				System.out.print("   ");
	
				System.out.print(ScreenIO.expandString( res.getString(i), 50)) ;
			        System.out.println();
			}
			System.out.println();
			ans = ScreenIO.promptForString("Press RETURN to continue ... ");
		}	
	   } catch (SQLException e) { e.printStackTrace();  /*System.exit(-1);*/ }
	     catch (NullPointerException e ) { e.printStackTrace(); }

	}

	protected void finalize() {
	   try { stmt.close(); res.close(); cnn.close(); } catch (SQLException e) {}
	}
}
